import requests
import base64
import hashlib
import datetime
import time
import os



URL_SERVER = 'http://127.0.0.1:8801'
URL_GET_RND = URL_SERVER + '/getRandom'
MAX_PACK_SIZE = 2048


def get_rnd(length):
    try:
        res = requests.get(url=URL_GET_RND, params={'bytes': length}, verify=False)
    except requests.exceptions.RequestException:
        return None
    if res.status_code != 200:
        return None
    return base64.b64decode(res.content)


def gen_file(dir, size):
    rnd = b''
    while True:
        l = len(rnd)
        if l >= size:
            break
        r = MAX_PACK_SIZE
        if size - l < MAX_PACK_SIZE:
            r = size - l
        d = get_rnd(r)
        if not d:
            time.sleep(5)
            continue
        else:
            rnd += d
            print(len(rnd))
    
    tmp_file = os.path.join(dir, 'temp.tmp')
    if os.path.isfile(tmp_file):
        os.remove(tmp_file)
    with open(tmp_file, 'wb') as file:
        file.write(rnd)

    fn = hashlib.md5(rnd).hexdigest() + '.rnd'
    os.rename(tmp_file, os.path.join(dir, fn))
    return fn

if __name__ == '__main__':
    
    fn = gen_file(r'C:\Users\firexmoon\Downloads\rnd', 1*1024*1024)
    print(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"), fn)